package wsz.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import wsz.util.ConstantsUtils;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 登录验证过滤
 * @author wsz
 * @date 2021/12/27 18:15
 **/
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        URI uri = request.getURI();
        String path = uri.getPath();

        /** 统一鉴权 **/
        if (path.contains("/user/info")) {
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            List<HttpCookie> httpCookies = cookies.get(ConstantsUtils.TOKEN);
            if (CollectionUtils.isEmpty(httpCookies)) {
                // token不存在
                response.setStatusCode(HttpStatus.SEE_OTHER);
                String data = "未登录，请先进行登录";
                return response.writeWith(Mono.just(response.bufferFactory().wrap(data.getBytes(StandardCharsets.UTF_8))));
            }
            HttpCookie httpCookie = httpCookies.get(0);
            String token = httpCookie.getValue();
            if (StringUtils.isEmpty(token)) {
                // token不存在
                response.setStatusCode(HttpStatus.SEE_OTHER);
                String data = "未登录，请先进行登录";
                return response.writeWith(Mono.just(response.bufferFactory().wrap(data.getBytes(StandardCharsets.UTF_8))));
            }
        }
        // 合法请求放行
        return chain.filter(exchange);
    }

    /**
     * 数值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
